<?php

namespace App\Http\Controllers\Home;


use App\Model\Project;
use App\Model\Company;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpWord\TemplateProcessor;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ProjectController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request){
        $query  = Project::where('id','!=','');
        if(!empty($_POST)){

            $data = $request->input();
            if (!empty($data['keywords'])){
                $query->where('project_name','like','%'.$data['keywords'].'%');
            }
        }
        $data = $query->orderBy('id','desc')->get();
        return view('project/index',[
            'data'=>$data
        ]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function one(Request $request){
        if(!empty($_POST)){
            $data = $request->input();
            if (empty($data['name'])){
                return back();
            }
            $one = Project::where('project_name','=',$data['name'])->get();
            $one = json_decode(json_encode($one), true);
            if (!empty($one)){
                return back();
            }
            $project = new Project();
            $project->project_name = $data['name'];
            $project->save();
//            dd($data);
            return back();
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request){
        if(!empty($_POST)){
            $data = $request->input();
            if (empty($data['name'])){
                return back();
            }

            Project::where('id','=',$data['project_id'])->update(['project_name'=>$data['name']]);
            return back();
        }
    }

    public function delete(Request $request)
    {
        $data = $request->input();
        $id = $data['id'];
        $result  = DB::delete('delete from project where id = ?',[$id]);
        echo json_encode($result);
        exit();
    }

    /*
     *参数:projectId 项目id
     *获取项目下的公司列表
     */
    public function company($projectId)
    {
        if(empty($projectId)) {
            \Session::flash('error', '参数错误!');
            return back();
        }

        $where = array();
        $where[] = array('project', $projectId);
        $field = array("id", "comName", "schedule", "project");
        $companies = Company::where($where)->get($field);

        return view('project.company', [
            'companies' =>$companies
        ]);
    }

}
